﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Windows.Forms;

namespace HTSManager
{
    public partial class Main : Form
    {
        //Platform platform;
        Securities securities;
        UserInfo userInfo;
        List<UserInfo> userInfoList;
        PlatformType g_platformType;                    //mug,tx,Q,FormDe
        ServerType g_serverType;                        //고객용,직원용
        ConnectionServerType g_connectionServerType;    //운영,테스트
        SettingTarketType g_settingTargetType;          //Platform, Manager

        public Main()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //rbManagerSave.Visible = false;

            //platform = new Platform();
            securities = new Securities();
            userInfoList = new List<UserInfo>();

            if (!LoadManagerDataFromReg())
            {
                MessageBox.Show("LoadManagerDataFromReg() error!");
                return;
            }

            userInfo = new UserInfo(g_platformType, g_settingTargetType);

            // 최초 targetPlatform 가져오기
            switch (g_platformType)
            {
                case PlatformType.MUG:
                    rbMug.Checked = true;
                    break;
                case PlatformType.TX:
                    rbTX.Checked = true;
                    break;
                case PlatformType.QTRADING:
                    rbQtrading.Checked = true;
                    break;
                case PlatformType.FORMDE:
                    rbFormDe.Checked = true;
                    break;
                default:
                    break;
            }

            switch (g_settingTargetType)
            {
                case SettingTarketType.PLATFORM:
                    rbLocalSave.Checked = true;
                    break;
                case SettingTarketType.MANAGER:
                    rbManagerSave.Checked = true;
                    break;
                default:
                    break;
            }

            // 설정 데이터 가져오기
            LoadSettingData();
            LoadSecuritySetting();

        }

        private bool LoadManagerDataFromReg()
        {
            RegistryKey rKey = Registry.CurrentUser.CreateSubKey(@"HTSManager");
            if (rKey != null)
            {
                // 플랫폼 읽어오기
                string strPlatform;
                if (rKey.GetValue("platform") == null)
                    strPlatform = "0";
                else
                    strPlatform = rKey.GetValue("platform").ToString();
                g_platformType = (PlatformType)Enum.Parse(typeof(PlatformType), strPlatform);

                // 로컬저장인지, 프로그램 저장인지 가져오기
                string strTarget;
                if (rKey.GetValue("target") == null)
                    strTarget = "0";
                else
                    strTarget = rKey.GetValue("target").ToString();
                g_settingTargetType = (SettingTarketType)Enum.Parse(typeof(SettingTarketType), strTarget);

                if(g_settingTargetType == SettingTarketType.MANAGER)
                    DeserializeUserInfo();
            }
            else
                return false;
            return true;
        }

        private bool SaveManagerDataToReg(PlatformType platformType, SettingTarketType settingTarketType)
        {
            if (settingTarketType == SettingTarketType.MANAGER)
                SerializeUserInfo();
            RegistryKey rKey = Registry.CurrentUser.CreateSubKey(@"HTSManager");
            if (rKey != null)
            {
                int nPlatformType = (int)platformType;
                int nSettingTarketType = (int)settingTarketType;
                rKey.SetValue("platform", nPlatformType.ToString());
                rKey.SetValue("target", nSettingTarketType.ToString());
            }
            else
                return false;
            return true;
        }

        private void LoadSettingData()
        {
            // 사용자 정보 가져오기
            //if (g_settingTargetType == SettingTarketType.PLATFORM)
            if (userInfo.SettingTarketType == SettingTarketType.PLATFORM)
                userInfo.GetUserInfo();
            else
            {
                List<UserInfo> userSelectedInfos = userInfoList.Where(c => c.PlatformType == g_platformType && c.ServerType == g_serverType && c.ConnectionServer == g_connectionServerType).ToList();
                if (userSelectedInfos.Count() != 0)
                {
                    userInfo = userSelectedInfos.FirstOrDefault(c => c.PlatformType == g_platformType && c.ServerType == g_serverType && c.ConnectionServer == g_connectionServerType);
                    cbServerInfo.DataSource = userSelectedInfos;
                    cbServerInfo.DisplayMember = "ServerIP";
                    cbUserInfo.DataSource = userSelectedInfos;
                    cbUserInfo.DisplayMember = "UserID";
                }
               // else
               //     userInfo = new UserInfo(g_platformType, SettingTarketType.MANAGER);
            }

            tbServer.Text = userInfo.ServerIP;
            tbUserId.Text = userInfo.UserID;
            tbPassword.Text = userInfo.UserPassword;
            tbCertPassword.Text = userInfo.UserCertPassword;
            cbMarketInquiry.Checked = userInfo.IsMarketInquary;
            cbForgery.Checked = userInfo.IsCheckForgery;

            // 고객용/직원용 구분
            if (userInfo.ServerType == ServerType.CUSTOMER)
                rbCustomer.Checked = true;
            if (userInfo.ServerType == ServerType.EMPOLYEE)
                rbEmployee.Checked = true;

            // 운영용/테스트용 구분
            if (userInfo.ConnectionServer == ConnectionServerType.OPERATION)
                rbOperationServer.Checked = true;
            if (userInfo.ConnectionServer == ConnectionServerType.TEST)
                rbTestServer.Checked = true;

            // 다운로드 구분
            switch (userInfo.DownloadType)
            {
                case DownloadType.NONE:
                    rbNoDown.Checked = true;
                    break;
                case DownloadType.ALL:
                    rbNormalDown.Checked = true;
                    break;
                case DownloadType.SCREEN:
                    rbScreenDown.Checked = true;
                    break;
                default:
                    break;
            }
            
            // 운영시 ip 지정
            switch (g_platformType)
            {
                case PlatformType.MUG:
                    if (userInfo.ServerType == ServerType.CUSTOMER)
                        tbServer.Text = "hts.wontrading.com";
                    else
                        tbServer.Text = "staff.wm.com";
                    break;
                case PlatformType.TX:
                    tbServer.Text = "hts.wontrading.com";
                    break;
                case PlatformType.QTRADING:
                    tbServer.Text = "newqtrade.wooriwm.com";
                    break;
                default:
                    break;
            }
        }

        private void SaveSettingData()
        {
            userInfo = new UserInfo(g_platformType, g_settingTargetType);
            // 사용자 정보 저장하기
            userInfo.ServerIP = tbServer.Text;
            userInfo.UserID = tbUserId.Text;
            userInfo.UserPassword = tbPassword.Text;
            userInfo.UserCertPassword = tbCertPassword.Text;
            userInfo.IsMarketInquary = cbMarketInquiry.Checked;
            userInfo.SetUserInfo();
            // 고객용/직원용 구분
            if (rbCustomer.Checked == true)
                userInfo.ServerType = ServerType.CUSTOMER;
            if (rbEmployee.Checked == true)
                userInfo.ServerType = ServerType.EMPOLYEE;

            // 운영용/테스트용 구분
            if (rbOperationServer.Checked == true)
                userInfo.ConnectionServer = ConnectionServerType.OPERATION;
            if (rbTestServer.Checked == true)
                userInfo.ConnectionServer = ConnectionServerType.TEST;
        }

        private void ClearSettingData()
        {
            userInfo.ServerIP = "";
            userInfo.UserID = "";
            userInfo.UserPassword = "";
            userInfo.UserCertPassword = "";
            
            /*
            tbServer.Clear();
            tbUserId.Clear();
            tbPassword.Clear();
            tbCertPassword.Clear();
             * */
        }

        private void LoadSecuritySetting()
        {
            // 방화벽 체크
            if (securities.isCheckFirewall == true)
                cbFirewall.Checked = true;
            else
                cbFirewall.Checked = false;

            // 키보드보안 체크
            if (securities.isCheckKeySecurity == true)
                cbKeySecurity.Checked = true;
            else
                cbKeySecurity.Checked = false;

            // AOS 체크
            if (securities.isCheckAOS == true)
                cbAOS.Checked = true;
            else
                cbAOS.Checked = false;
        }

        private void rbMug_CheckedChanged(object sender, EventArgs e)
        {
            if (rbMug.Checked == true)
            {
                userInfo.PlatformType = PlatformType.MUG;
                g_platformType = PlatformType.MUG;
                rbEmployee.Enabled = true;
                LoadSettingData();
            }
            else
                rbEmployee.Enabled = false;
        }

        private void rbTX_CheckedChanged(object sender, EventArgs e)
        {
            if (rbTX.Checked == true)
            {
                userInfo.PlatformType = PlatformType.TX;
                g_platformType = PlatformType.TX;
                LoadSettingData();
            }
        }

        private void rbQtrading_CheckedChanged(object sender, EventArgs e)
        {
            if (rbQtrading.Checked == true)
            {
                userInfo.PlatformType = PlatformType.QTRADING;
                g_platformType = PlatformType.QTRADING;
                LoadSettingData();
            }
        }

        private void rbFormDe_CheckedChanged(object sender, EventArgs e)
        {
            if (rbFormDe.Checked == true)
            {
                userInfo.PlatformType = PlatformType.FORMDE;
                g_platformType = PlatformType.FORMDE;
                rbCustomer.Enabled = false;
                rbEmployee.Enabled = true;
                rbEmployee.Checked = true;
                rbOperationServer.Enabled = false;
                tbPassword.Enabled = false;
                tbCertPassword.Enabled = false;
                cbMarketInquiry.Enabled = false;
                rbTestServer.Checked = true;
                rbNoDown.Enabled = false;
                rbScreenDown.Enabled = false;
                rbNormalDown.Enabled = false;
                LoadSettingData();
            }
            else
            {
                rbCustomer.Enabled = true;
                rbEmployee.Enabled = false;
                rbOperationServer.Enabled = true;
                tbPassword.Enabled = true;
                tbCertPassword.Enabled = true;
                cbMarketInquiry.Enabled = true;
                rbNoDown.Enabled = true;
                rbScreenDown.Enabled = true;
                rbNormalDown.Enabled = true;
            }
        }

        private void rbOperationServer_CheckedChanged(object sender, EventArgs e)
        {
            if (rbOperationServer.Checked == true)
            {
                //cbServerInfo.Enabled = false;
                tbServer.Enabled = false;
                userInfo.ConnectionServer = ConnectionServerType.OPERATION;
                g_connectionServerType = ConnectionServerType.OPERATION; ;
                LoadSettingData();
            }
            else
            {
                //cbServerInfo.Enabled = true;
                tbServer.Enabled = true;
            }
        }

        private void rbTestServer_CheckedChanged(object sender, EventArgs e)
        {
            if (rbTestServer.Checked == true)
            {
                userInfo.ConnectionServer = ConnectionServerType.TEST;
                g_connectionServerType = ConnectionServerType.TEST;
                if (g_platformType == PlatformType.MUG && userInfo.ServerType == ServerType.CUSTOMER || g_platformType == PlatformType.TX)
                    LoadSettingData();
            }
        }

        private void rbCustomer_CheckedChanged(object sender, EventArgs e)
        {
            if (rbCustomer.Checked == true)
            {
                userInfo.ServerType = ServerType.CUSTOMER;
                g_serverType = ServerType.CUSTOMER;
                LoadSettingData();
            }
        }

        private void rbEmployee_CheckedChanged(object sender, EventArgs e)
        {
            if (rbEmployee.Checked == true)
            {
                userInfo.ServerType = ServerType.EMPOLYEE;
                g_serverType = ServerType.EMPOLYEE;
                LoadSettingData();
            }

        }

        private void rbLocalSave_CheckedChanged(object sender, EventArgs e)
        {
            if (rbLocalSave.Checked == true)
            {
                g_settingTargetType = SettingTarketType.PLATFORM;
                userInfo.SettingTarketType = SettingTarketType.PLATFORM;
                LoadSettingData();
                btModifyUserInfo.Enabled = false;
                btInsertUserInfo.Enabled = false;
                btDeleteUserInfo.Enabled = false;
                cbUserInfo.Enabled = false;
                cbServerInfo.Enabled = false;
            }
            else
                ClearSettingData();
        }

        private void rbManagerSave_CheckedChanged(object sender, EventArgs e)
        {
            if (rbManagerSave.Checked == true)
            {
                g_settingTargetType = SettingTarketType.MANAGER;
                userInfo.SettingTarketType = SettingTarketType.MANAGER;
                LoadSettingData();
                btModifyUserInfo.Enabled = true;
                btInsertUserInfo.Enabled = true;
                btDeleteUserInfo.Enabled = true;
                cbUserInfo.Enabled = true;
                cbServerInfo.Enabled = true;
                //tbServer.Enabled = true;
            }
        }

        private void cbMarketInquiry_CheckedChanged(object sender, EventArgs e)
        {
            if (cbMarketInquiry.Checked == true)
                tbCertPassword.Enabled = false;
            else
                tbCertPassword.Enabled = true;
        }

        private void cbForgery_CheckedChanged(object sender, EventArgs e)
        {
            if (cbForgery.Checked == false)
                userInfo.IsCheckForgery = false;
            else
                userInfo.IsCheckForgery = true;            
        }

        private void cbFirewall_CheckedChanged(object sender, EventArgs e)
        {
            if (cbFirewall.Checked == false)
                securities.isCheckFirewall = false;
            else
                securities.isCheckFirewall = true;
        }

        private void cbKeySecurity_CheckedChanged(object sender, EventArgs e)
        {
            if (cbKeySecurity.Checked == false)
                securities.isCheckKeySecurity = false;
            else
                securities.isCheckKeySecurity = true;
        }

        private void cbAOS_CheckedChanged(object sender, EventArgs e)
        {
            if (cbAOS.Checked == false)
                securities.isCheckAOS = false;
            else
                securities.isCheckAOS = true;
        }

        private void btRecover_Click(object sender, EventArgs e)
        {
            MessageBox.Show("아직 안만들었어요 ㅠㅠ");
        }

        private void btExecute_Click(object sender, EventArgs e)
        {
            if (tbPassword.Text.Length == 0 && g_platformType != PlatformType.FORMDE)
            {
                MessageBox.Show("비밀번호를 입력해주세요");
                return;
            }
            SaveSettingData();
            string programPath = userInfo.strExecuteFilePath;
            Process.Start(programPath, " /U" + tbUserId.Text + " /P" + tbPassword.Text + " /C" + tbCertPassword.Text);
        }


        private void btInsertUserInfo_Click(object sender, EventArgs e)
        {
            SaveSettingData();
            UserInfo userInfoLocal = (UserInfo)userInfo.Clone();
            userInfoList.Add(userInfoLocal);
            //cbUserInfo.Items.Add(userInfo.UserID);
            //cbServerInfo.Items.Add(userInfo.ServerIP);
            cbServerInfo.Items.Insert(0, userInfo.ServerIP);
            cbServerInfo.SelectedIndex = 0;
            cbUserInfo.Items.Insert(0, userInfo.UserID);
            cbUserInfo.SelectedIndex = 0;
            
        }

        private void cbServerInfo_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void cbUserInfo_SelectedIndexChanged(object sender, EventArgs e)
        {
            //userInfo = userInfoList.ElementAt(cbUserInfo.SelectedIndex);
            //LoadSettingData();
        }

        private void Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            SaveManagerDataToReg(userInfo.PlatformType, userInfo.SettingTarketType);
        }

        private void rbNormalDown_CheckedChanged(object sender, EventArgs e)
        {
            if (rbNormalDown.Checked == true)
            {
                userInfo.DownloadType = DownloadType.ALL;
            }
        }

        private void rbScreenDown_CheckedChanged(object sender, EventArgs e)
        {
            if (rbScreenDown.Checked == true)
            {
                userInfo.DownloadType = DownloadType.SCREEN;
            }
        }

        private void rbNoDown_CheckedChanged(object sender, EventArgs e)
        {
            if (rbNoDown.Checked == true)
            {
                userInfo.DownloadType = DownloadType.NONE;
            }
        }


        private string xmlFilename = @"C:\WMP\UserInfoList.dat";

        public void SerializeUserInfo()
        {
            BinaryFormatter binFmt = new BinaryFormatter();
            using (FileStream fs = new FileStream(xmlFilename, FileMode.Create))
            {
                try
                {
                    binFmt.Serialize(fs, userInfoList);
                }
                catch (Exception)
                {
                    MessageBox.Show("사용자정보 저장 중 문제가 발생하였습니다.");
                    throw;
                }
            }
        }

        public void DeserializeUserInfo()
        {
            BinaryFormatter binFmt = new BinaryFormatter();
            if (!File.Exists(xmlFilename))
                return;
            using (FileStream rdr = new FileStream(xmlFilename, FileMode.Open))
            {
                try
                {
                    userInfoList = (List<UserInfo>)binFmt.Deserialize(rdr);
                }
                catch (Exception)
                {
                    MessageBox.Show("사용자정보 로딩 중 문제가 발생하였습니다. %s파일을 삭제해주세요.",xmlFilename);
                    throw;
                }
                
            }
        }

    }
}
